from flask import Flask, request, render_template, make_response, jsonify, redirect, url_for
import requests
import re
from urllib.parse import quote

app = Flask(__name__)

def extract_guide_id(url):
    pattern = r'casecenter/([a-f0-9]{32})'
    match = re.search(pattern, url)
    return match.group(1) if match else None

def query_huawei_api(guide_id):
    url = "https://devstation-svc.connect.huaweicloud.com/userApi/clouddeployso/userGuide/queryApprovedUserGuideById"
    headers = {
        "Content-Type": "application/json",
        "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.124 Safari/537.36"
    }
    payload = {"guideId": guide_id, "language": "zh"}
    
    try:
        response = requests.post(url, json=payload, headers=headers)
        response.raise_for_status()
        data = response.json()
        
        if 'result' not in data:
            return {"error": "API返回数据结构异常"}
            
        result_data = data['result']
        return {
            "name": result_data.get("name", "无标题"),
            "introduce": result_data.get("introduce", "暂无介绍"),
            "content": result_data.get("content", "暂无内容")
        }
    except Exception as e:
        return {"error": f"处理失败: {str(e)}"}

@app.route('/', methods=['GET', 'POST'])
def index():
    defaultResult={"name": "无标题", "introduce": "暂无介绍", "content": "暂无内容"}
    defaultUrl = request.form.get('url')
    url = defaultUrl if defaultUrl is not None else ''
    print(url)
    if request.method == 'POST':
        if not url:
            return render_template('index.html', error="请输入URL", result=defaultResult)
        
        guide_id = extract_guide_id(url)
        if not guide_id:
            return render_template('index.html', error="无效的URL格式", result=defaultResult)
        
        result = query_huawei_api(guide_id)

        return render_template('index.html', result=result, url=url, error="")
    
    # GET请求时返回带有默认值的空页面
    return render_template('index.html', result=defaultResult, error="", url=url)

@app.route('/clean', methods=['POST'])
def clean():
    defaultResult={"name": "无标题", "introduce": "暂无介绍", "content": "暂无内容"}
    return render_template('index.html', result=defaultResult, error="", url="")

@app.route('/download', methods=['POST'])
def download():
    try:
        data = request.get_json()
        content = data.get('content', '')
        filename = data.get('filename', '华为案例.md')
        
        if not content:
            return jsonify({"error": "没有可下载的内容"}), 400
        
        filename = re.sub(r'[\\/*?:"<>|]', "", filename)
        if not filename.endswith('.md'):
            filename += '.md'
        
        response = make_response(content)
        response.headers['Content-Type'] = 'text/markdown; charset=utf-8'
        response.headers['Content-Disposition'] = f'attachment; filename="{quote(filename)}"'
        return response
    except Exception as e:
        return jsonify({"error": str(e)}), 500

if __name__ == '__main__':
    app.run(host='127.0.0.1', port=5001, debug=True)